package com.ethereal.petmanagement.dao.impl;

import com.ethereal.petmanagement.dao.IUserDao;
import com.ethereal.petmanagement.dto.UserDTO;
import com.ethereal.petmanagement.util.DatabaseUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements IUserDao {
    @Override
    public UserDTO findUserByUsername(UserDTO userDTO) {
        String sql = "select * from user where username = ?";
        try(
                Connection conn = DatabaseUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql);
                ){
            pstmt.setString(1, userDTO.getUsername());
            try(ResultSet rs = pstmt.executeQuery()){
                if (rs.next()){
                    userDTO.setUsername(rs.getString("username"));
                    userDTO.setPassword(rs.getString("password"));
                    userDTO.setSalt(rs.getString("salt"));
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return userDTO;
    }

    @Override
    public Boolean insertUser(UserDTO userDTO) {
        System.out.println("Dao");
        String sql = "insert into user (id, username, password, phone, salt) values (?, ?, ?, ?, ?)";
        System.out.println("sql");
        try(
                Connection conn = DatabaseUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql);
        ){
            pstmt.setLong(1, userDTO.getId());
            pstmt.setString(2, userDTO.getUsername());
            pstmt.setString(3, userDTO.getPassword());
            pstmt.setString(4, userDTO.getPhone());
            pstmt.setString(5, userDTO.getSalt());
            System.out.println("ok");
            if (pstmt.executeUpdate() == 1){
                System.out.println("success!");
                return true;
            }
            System.out.println("error!");
            return false;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
